#!/usr/bin/env python3
#created by anchengan in 20250314
import utils.threading as threading
import paks.requests as requests
import utils.socket as socket
import utils.argparse as argparse
from utils.watchdog import watchdog_server
from utils.checker import is_valid_ipv4,is_valid_port
from utils.acaboard import run_server
from utils.ID_tools import create_data
def main():

    # create ArgumentParser object
    parser = argparse.ArgumentParser(
        description="Acautoai-master is the core of the Acautoai system, used to manage various algorithm services."
    )
 
    # add argument
    parser.add_argument(
        '-ho', '--host', 
        type=str, 
        required=True, 
        help='host of Acautoai-master'
    )
    
    parser.add_argument(
        '-po', '--port', 
        type=int, 
        required=True,
        help='port of Acautoai-master'
    )
    
    parser.add_argument(
        '-d', '--debug', 
        action='store_true', 
        help='debug mode'
    )
 
    # parse argument
    args = parser.parse_args()
    host = args.host
    port = args.port
    if is_valid_ipv4(host) is not True:
        raise ValueError("The format of the host set is incorrect. format:xx.xx.xx.xx")
    if is_valid_port(port) is not True:
        raise ValueError("The format of the port set is incorrect, 0 <= port <= 65530.")
    # use argument
    if args.debug:
        print(f"debug mode!")
    masterip='0.0.0.0'
    masterport=65532
    masterurl = f'http://{masterip}:{masterport}'
    board_thread=threading.Thread(target=run_server,args=[masterip,masterport])
    board_thread.start()
    watchdog_thread=threading.Thread(target=watchdog_server,args=[masterip,masterport])
    watchdog_thread.start()
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        try:
            s.bind((host, port))
            s.listen()
            print(f"Server listening on {host}:{port}")

            while True:
                conn, _ = s.accept()
                data = conn.recv(1024).decode('utf-8')
                if args.debug:
                    print(data)
                dataparse=data.split("-")

                data_send=create_data(dataparse[0],dataparse[1],dataparse[2],dataparse[3],dataparse[4])
                resp = requests.post(masterurl, data=data_send)
                if args.debug:
                    print(resp.text)
                conn.sendall(resp.text.encode('utf-8'))  # Echo the received data back to the client
        except:
            s.close()
    s.close()

 
if __name__ == "__main__":
    main()
